package com.sfd.api.exception;

import com.sfd.core.exception.SfdBootException;
import com.sfd.core.module.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;

import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * sfd 异常处理器
 *
 * @author haden
 * @date 2022/8/13 22:08
 **/
@RestControllerAdvice
@Slf4j
public class SfdExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(SfdBootException.class)
    public Result<?> handleRRException(SfdBootException e) {
        log.error(e.getMessage(), e);
        return Result.sysError(e.getMessage());
    }

    /**
     * token校验异常
     *
     * @param e 异常
     * @return 默认处理
     */
    @ExceptionHandler({AuthenticationException.class})
    public Result<?> handleAuthenticationException(AuthenticationException e) {
        log.error(e.getMessage(), e);
        return Result.noauth(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e){
        log.error(e.getMessage(), e);
        return Result.sysError("操作失败，"+e.getMessage());
    }

    /**
     * @Author 政辉
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        StringBuffer sb = new StringBuffer();
        sb.append("不支持");
        sb.append(e.getMethod());
        sb.append("请求方法，");
        sb.append("支持以下");
        String [] methods = e.getSupportedMethods();
        if(methods!=null){
            for(String str:methods){
                sb.append(str);
                sb.append("、");
            }
        }
        log.error(sb.toString(), e);
        return Result.sysError(sb.toString());
    }

}
